package com.siss.tenancy.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil extends com.github.pagehelper.StringUtil {

    private static SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyyMMddHHmmss");
    private static SimpleDateFormat DATE_TEXT_FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    /**
     * String转Date
     * 
     * @param date
     * @param format
     *     日期格式（默认：yyyy-MM-dd HH:mm:ss）
     * @return
     */
    public static Date date(String date, String format) {
        if (StringUtil.isNotEmpty(date)) {
            if (StringUtil.isEmpty(format)) {
                format = "yyyy-MM-dd HH:mm:ss";
            }
            try {
                Date dates = new SimpleDateFormat(format).parse(date);
                return dates;
            } catch (ParseException e) {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 转成String,类型=yyyyMMddHHmmss
     * 
     * @param date
     * @return
     */
    public static String DateToTimeStr(Date date) {
        return date == null ? "" : DATE_FORMATTER.format(date);
    }

    /**
     * 转成String,类型=yyyy-MM-dd HH:mm
     * 
     * @param date
     * @return
     */
    public static String getDateText(Date date) {
        return date == null ? "" : DATE_TEXT_FORMATTER.format(date);
    }

    /**
     * 转成String类型，失败返回""
     * 
     * @param str
     * @return
     */
    public static String trim(String str) {
        return str == null ? "" : str.trim();
    }

    /**
     * 转换成String类型，defult = 失败时返回
     * 
     * @param str
     * @param defult
     * @return
     */
    public static String trim(String str, String defult) {
        return str == null ? trim(defult) : str.trim();
    }

    /**
     * 判断List是否为空
     * 
     * @param arr
     * @return
     */
    public static boolean isEmptyArray(String[] arr) {
        if ((arr == null) || (arr.length == 0)) {
            return true;
        }
        return false;
    }

    /**
     * 切割
     * 
     * @param src
     * @param oldStr
     * @param newStr
     * @return
     */
    public static String replace(String src, String oldStr, String newStr) {
        StringBuffer result = new StringBuffer();
        boolean found = false;
        if ((src == null) || (oldStr == null) || (newStr == null)) {
            throw new NullPointerException("parameter is null");
        }
        if (oldStr.length() == 0) {
            throw new IllegalArgumentException("illegal parameter");
        }
        int pos = 0;
        int pos1 = 0;
        while (pos < src.length()) {
            pos1 = src.indexOf(oldStr, pos);
            if (pos1 < 0) {
                pos1 = src.length();
                found = false;
            } else {
                found = true;
            }
            result.append(src.substring(pos, pos1));
            if (found) {
                result.append(newStr);
                pos = pos1 + oldStr.length();
            } else {
                pos = pos1;
            }
        }
        return result.toString();
    }

    /**
     * 长度计算
     * 
     * @param src
     * @param key
     * @return
     */
    public static int count(String src, String key) {
        int count = 0;
        for (String temp = src; temp.indexOf(key) >= 0; temp = temp.substring(temp.indexOf(key) + key.length())) {
            count++;
        }
        return count;
    }

    /**
     * 转换成int类型，失败返回-1
     * 
     * @param str
     * @return
     */
    public static int getAsInt(String str) {
        return getAsInt(str, -1);
    }

    /**
     * 转换成int类型，defaultv = 失败时返回
     * 
     * @param str
     * @param defaultv
     * @return
     */
    public static int getAsInt(String str, int defaultv) {
        if ((str == null) || ("".equals(str))) {
            return defaultv;
        }
        try {
            return Integer.parseInt(str, 10);
        } catch (Exception e) {
        }
        return defaultv;
    }

    /**
     * 转换成Long类型，失败时返回-1
     * 
     * @param str
     * @return
     */
    public static long getAsLong(String str) {
        return getAsLong(str, -1L);
    }

    /**
     * 转换成Long类型，defaultv = 失败时返回
     * 
     * @param str
     * @param defaultv
     * @return
     */
    public static long getAsLong(String str, long defaultv) {
        if ((str == null) || ("".equals(str))) {
            return defaultv;
        }
        try {
            return Long.parseLong(str, 10);
        } catch (Exception e) {
        }
        return defaultv;
    }

    public static String[] split(String str, String seperator) {
        return split(str, seperator, false);
    }

    public static String[] split(String str, String seperator, boolean tail) {
        if ((str == null) || (str.equals("")) || (trim(seperator).equals(""))) {
            return tail ? new String[] { "" } : new String[0];
        }
        if ((!tail) && (str.endsWith(seperator))) {
            str = str.substring(0, str.length() - seperator.length());
        }
        ArrayList temp = new ArrayList();
        int oldPos = 0;
        int newPos = str.indexOf(seperator);
        int parentLength = str.length();
        int subStrLength = seperator.length();
        if (newPos != -1) {
            newPos += subStrLength;
        }
        while ((newPos <= parentLength) && (newPos != -1)) {
            temp.add(str.substring(oldPos, newPos - subStrLength));
            oldPos = newPos;
            newPos = str.indexOf(seperator, oldPos);
            if (newPos != -1) {
                newPos += seperator.length();
            }
        }
        if (oldPos <= parentLength) {
            temp.add(str.substring(oldPos));
        }
        return (String[]) temp.toArray(new String[temp.size()]);
    }

    /**
     * 转成String类型， defult=失败时返回的类型
     * 
     * @param obj
     * @param defult
     * @return
     */
    public static String trim(Object obj, String defult) {
        return obj == null ? trim(defult) : obj.toString().trim();
    }

    /**
     * 转换成String，失败返回""
     * 
     * @param str
     * @return
     */
    public static String trim(Object str) {
        return str == null ? "" : str.toString().trim();
    }

    /**
     * 转换成Double类型，失败返回0.0
     * 
     * @param str
     * @return
     * @throws Exception
     * @throws NumberFormatException
     */
    public static double getDouble(String str) throws Exception, NumberFormatException {
        return getDouble(str, 0.0D);
    }

    /**
     * 转换成Double类型，defaultValue是转换失败时返回的值
     * 
     * @param str
     * @param defaultValue
     * @return
     * @throws Exception
     * @throws NumberFormatException
     */
    public static double getDouble(String str, double defaultValue) throws Exception, NumberFormatException {
        if (!hasText(str)) {
            return defaultValue;
        }
        try {
            return Double.parseDouble(str);
        } catch (NumberFormatException numberformatexception) {
        }
        return defaultValue;
    }

    public static boolean hasText(String str) {
        return !"".equals(nonNull(str));
    }

    public static String nonNull(String str) {
        return str == null ? "" : str;
    }

    /**
     * 将汉字转换成全拼音
     * 
     * @param src
     * @return
     */
    public static String getPingYin(String src) {
        char[] t1 = null;
        t1 = src.toCharArray();
        String[] t2 = new String[t1.length];
        HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();

        t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        t3.setVCharType(HanyuPinyinVCharType.WITH_V);
        String result = "";
        int length = t1.length;

        try {
            for (int i = 0; i < length; i++) {
                // 判断是否为汉字字符
                if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
                    t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
                    result += t2[0];
                } else
                    result += Character.toString(t1[i]);
            }
            return result;
        } catch (BadHanyuPinyinOutputFormatCombination e1) {
            e1.printStackTrace();
        }
        return result;
    }

    /**
     * 将汉字转换成首字母
     * 
     * @param str
     * @return
     */
    public static String getPinYinHeadChar(String str) {

        String convert = "";
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        return convert;
    }

    /**
     * 功能描述：利用正则表达式，提取匹配字符串集合
     * 作 者： wangxj
     * 创建时间： 2018/11/14 16:36
     * 
     * @param strings 字符串
     * @param regex 正则表达式
     *     返回值： java.util.List<java.lang.String>
     */
    public static List<String> getStringListByRegex(String strings, String regex) {
        List<String> stringList = new ArrayList<String>();
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(strings);
        while (m.find()) {
            stringList.add(m.group());
        }
        return stringList;
    }

    /**
     * 方法名: vagueStr
     * 描述: 模糊处理字符串，中间三分之一长度做模糊处理
     * 返回类型： String
     * 
     * @param str
     * @return
     * 作者：wangxj
     * 创建时间：2018年5月29日 下午3:45:55
     */
    public static String vagueStr(String str) {
        if (null != str) {
            int idNolen = str.length();
            if (idNolen > 0) {
                int vaguelen = idNolen / 3;
                if (vaguelen > 0) {
                    String headStr = str.substring(0, vaguelen);
                    String vagueStr = "";
                    for (int i = 0; i < vaguelen; i++) {
                        vagueStr += "*";
                    }
                    String endStr = str.substring(headStr.length() + vagueStr.length());
                    str = headStr + vagueStr + endStr;
                }
            }
        }
        return str;
    }

    public static String vagueStr(String idNo, Integer showNnumber) {
        if (null != idNo || idNo.length() > 0 || showNnumber == 0) {
            if (showNnumber >= idNo.length()) {
                return idNo;
            }

            Integer headNumber = idNo.length() - showNnumber;
            Integer number = headNumber - showNnumber;
            String headStr = idNo.substring(0, showNnumber);
            String str = "";
            for (int i = 0; i < number; i++) {
                str += "*";
            }

            String endStr = idNo.substring(headStr.length() + str.length(), idNo.length());
            idNo = headStr + str + endStr;
        }
        return idNo;
    }

    /**
     * 根据键值对填充字符串，如("hello ${name}",{name:"xiaoming"})
     * 输出：
     * 
     * @param content
     * @param map
     * @return
     */
    public static String renderString(String content, Map<String, String> map) {
        Set<Map.Entry<String, String>> sets = map.entrySet();
        for (Map.Entry<String, String> entry : sets) {
            String regex = "\\$\\{" + entry.getKey() + "\\}";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(content);
            if (null != entry.getValue()) {
                content = matcher.replaceAll(entry.getValue());
            }
        }
        return content;
    }
}
